package org.vectrics.user;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;

public class StringEncryptor {
	public final static String ALGORITHM_DES = "DES";
	private javax.crypto.spec.SecretKeySpec keySpec;
	private byte[] key;
	private String algorithm;
	private Logger log = Logger.getLogger(this.getClass());
	
	/** Creates a new instance of Crypt */
	public StringEncryptor(String key, String algorithm) {
		this.key = key.getBytes();
		this.algorithm = algorithm;
		this.keySpec = new javax.crypto.spec.SecretKeySpec(this.key,
		this.algorithm);
	}

	/** Encrypts the give String to an array of bytes */
	public byte[] encryptString(String text) {
		try {
			javax.crypto.Cipher cipher =
			javax.crypto.Cipher.getInstance(this.algorithm);
			cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, this.keySpec);
			return cipher.doFinal(text.getBytes());
		} catch (Exception e) {
			log.error("Exception encrypting text", e);
			return null;
		}
	}

	public String decryptString(String hex) {
		return this.decryptString(this.toByteArray(hex));
	}

	/** Decrypts the given array of bytes to a String */
	public String decryptString(byte[] b) {
		try {
			javax.crypto.Cipher cipher =
			javax.crypto.Cipher.getInstance(this.algorithm);
			cipher.init(javax.crypto.Cipher.DECRYPT_MODE, this.keySpec);
			return new String(cipher.doFinal(b));
		} catch (Exception e) {
			log.error("Exception decrypting text: " + toHex(b), e);
			throw new SystemException("Exception decrypting text: " + toHex(b), e);
		}
	}

	
	/** Converts the given array of bytes to a hex String */
	public static String toHex(byte[] buf) {
		char[] cbf=new char[buf.length*2];
		for (int jj=0, kk=0; jj<buf.length; jj++) {
			cbf[kk++]="0123456789ABCDEF".charAt((buf[jj]>>4) & 0x0F);
			cbf[kk++]="0123456789ABCDEF".charAt(buf[jj] & 0x0F);
		}
		return new String(cbf);
	}

	/** Converts a valid hex String to an array of bytes */
	public static byte[] toByteArray(String hex) {
		byte[] result=new byte[hex.length()/2];
		for (int jj=0, kk=0; jj<result.length; jj++) {
			result[jj]=(byte)(
			("0123456789ABCDEF".indexOf(hex.charAt(kk++))<<4)+
			"0123456789ABCDEF".indexOf(hex.charAt(kk++)));
		}
		return result;
	}
	
}
